import {defineComponent, provide, ref, onMounted, watch} from "vue";
import {TabPaneContext, TabsKey} from "./types";
import './index.scss';

export default defineComponent({
  name: 'Tabs',
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue'],
  setup(props, { slots, emit }) {
    const panels = ref<TabPaneContext[]>([]);
    const currentTab = ref(props.modelValue);

    const addPanel = (item: TabPaneContext): void => {
      panels.value.push(item);
    }
    const removePanel = (name: string): void => {
      if (panels.value.length) {
        const index = panels.value.findIndex(item => item.name === name);
        if (index > -1) {
          panels.value.splice(index, 1);
        }
      }
    }
    provide(TabsKey, { addPanel, removePanel });

    const tabClick = (name: string) => {
      if (name !== currentTab.value) {
        emit('update:modelValue', name);
      }
    }

    const renderNavs = (): JSX.Element[] => {
      return panels.value.map(item => {
        const extraCls = item.name === currentTab.value ? 'active' : '';
        return <div class={ 'ant-tab-pane ' + extraCls } onClick={ tabClick.bind(this, item.name) }>
            { item.titleSlot ? item.titleSlot({ name: item.name }) : item.name }
          </div>;
      });
    }

    const renderContent = (): JSX.Element => {
      if (panels.value.length) {
        return panels.value.map(item => item.defSlot());
      }
      return '';
    }

    onMounted(() => {
      if (!currentTab.value && panels.value.length) {
        emit('update:modelValue', panels.value[0].name);
      }
    });

    const updatePaneVisible = (): void => {
      if (panels.value.length) {
        panels.value.forEach(item => {
          item.changeVisible(item.name === currentTab.value);
        });
      }
    }

    watch(() => props.modelValue, newVal => {
      currentTab.value = newVal;
      updatePaneVisible();
    });

    return () => {
      const content = renderContent();
      return (
        <div class="ant-tabs">
          <div class="navs">
            { renderNavs() }
          </div>
          { slots.default!() }
        </div>
      );
    }
  }
});
